package cn.practice.chat.stream;

import cn.practice.chat.enums.ChatTypeEnum;
import cn.practice.chat.lang.Result;
import cn.practice.chat.message.MqMessage;
import cn.practice.chat.response.chat.GroupUserResponse;
import cn.practice.chat.response.message.MessageRecord;
import cn.practice.chat.user.feign.UserApiFeign;
import com.alibaba.fastjson.JSONObject;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.function.Consumer;

import static cn.practice.chat.handler.ChannelMap.CHANNEL_MAP;

/**
 * @ClassName MessageListener
 * @Description:
 * @Author A-TAO
 * @Date 2022/11/8
 * @Version V1.0
 **/
@Slf4j
@Component
public class MessageListener {

    @Autowired
    private UserApiFeign userApiFeign;

    @Bean
    public Consumer<MqMessage> wechat(){
        return message -> {

            log.info("收到mq消息，{}", message);
            MessageRecord record = message.getRecord();
            String sendUser = record.getUsername();
            if(record.getType().equals(ChatTypeEnum.SingleChat.getType())){
                if(CHANNEL_MAP.containsKey(record.getFriendName())){
                    CHANNEL_MAP.get(record.getFriendName()).writeAndFlush(new TextWebSocketFrame(String.valueOf(JSONObject.toJSON(record))));
                }
            }else {
                // 群聊消息 通知群里的每一个人
                Integer groupId = record.getFriendId();
                Result<List<GroupUserResponse>> listResult = userApiFeign.getGroupUserIds(groupId);
                List<GroupUserResponse> groupUsers = listResult.getData();
                if(!CollectionUtils.isEmpty(groupUsers)){
                    for(GroupUserResponse user:groupUsers){
                        if(!sendUser.equals(user.getUsername())){
                            if(CHANNEL_MAP.containsKey(user.getUsername())){
                                CHANNEL_MAP.get(user.getUsername()).writeAndFlush(new TextWebSocketFrame(String.valueOf(JSONObject.toJSON(record))));
                            }
                        }
                    }
                }
        }


        };
    }



}
